'use client';

import type { IPostEditInfo, IPostNewInfo, IPostTemplate } from '@/interfaces';
import { useQuery } from '@tanstack/react-query';
import { queryPostTemplateBySection } from '@/services/api';
import Alert from '@/app/[locale]/alert/alert';
import AlertLoad from '@/app/[locale]/alert/load';
import classNames from 'classnames';
import { useContext, useState } from 'react';
import ContentHtml from '@/app/[locale]/common/content/html';
import Nodata from '@/app/[locale]/common/nodata/nodata';
import { PostEditContext } from '@/contexts/post-edit';
import Link from 'next/link';
import { usePathname } from 'next/navigation';

export type TTemplateTranslatedField =
  | 'nodata'
  | 'apply'
  | 'overview'
  | 'content';

export default function PostTemplate(
  this: any,
  {
    source,
    translatedFields = {
      nodata: '暂无模板',
      apply: '应用',
      overview: '说明',
      content: '模板',
    },
  }: {
    source: IPostEditInfo | IPostNewInfo;
    translatedFields?: Record<TTemplateTranslatedField, any>;
  },
) {
  const isEdit = 'basic' in source;
  const { onNavItemName } = useContext(PostEditContext);
  const [currentItem, setCurrentItem] = useState<IPostTemplate>();
  const sectionId = isEdit
    ? source.section.id
    : source.sections[0]
    ? source.sections[0].id
    : undefined;
  const pathname = usePathname();

  const queryPostTemplateBySectionQuery = useQuery(
    ['/forum', '/templates', '/sections', sectionId],
    async (context) => {
      return (await queryPostTemplateBySection({
        id: context.queryKey[3],
      })) as IPostTemplate[];
    },
    {
      enabled: !!sectionId,
    },
  );

  function onClickItem(item: IPostTemplate) {
    setCurrentItem(item);
  }

  function onClickApply() {
    onNavItemName('编辑');
  }

  if (queryPostTemplateBySectionQuery.data) {
    const data = queryPostTemplateBySectionQuery.data;

    return (
      <div className="card border-0">
        <div className="card-body d-flex flex-column gap-4 my-4">
          {data.length > 0 && (
            <div className="row g-4">
              <div className="col">
                <div className="list-group">
                  {data.map((item) => {
                    return (
                      <button
                        onClick={onClickItem.bind(this, item)}
                        key={item.id}
                        type="button"
                        className={classNames(
                          'list-group-item list-group-item-action',
                          currentItem && currentItem.id === item.id
                            ? 'active'
                            : false,
                        )}
                        aria-current="true"
                      >
                        {item.name}
                      </button>
                    );
                  })}
                </div>
              </div>
              {currentItem && (
                <div className="col-12">
                  <Link
                    className="btn btn-primary col-3"
                    href={pathname.replace(
                      '/template',
                      `?template=${currentItem.id}&template-sid=${sectionId}`,
                    )}
                    onClick={onClickApply}
                  >
                    {translatedFields.apply}
                  </Link>

                  <div className="card">
                    <div className="card-header">
                      {translatedFields.overview}
                    </div>
                    <div className="card-body">
                      {currentItem.overview ? (
                        <ContentHtml content={currentItem.overview} />
                      ) : (
                        <Nodata />
                      )}
                    </div>
                  </div>

                  <div className="card">
                    <div className="card-header">
                      {translatedFields.content}
                    </div>
                    <div className="card-body">
                      {currentItem.content ? (
                        <ContentHtml content={currentItem.content} />
                      ) : (
                        <Nodata />
                      )}
                    </div>
                  </div>
                </div>
              )}
            </div>
          )}

          {data.length === 0 && <Nodata />}
        </div>
      </div>
    );
  }

  if (queryPostTemplateBySectionQuery.error) {
    return (
      <Alert type="error" message={queryPostTemplateBySectionQuery.error} />
    );
  }

  return <AlertLoad />;
}
